package com.lmy.androidcustomview.touch.drag

import android.content.ClipData
import android.content.Context
import android.util.AttributeSet
import android.view.DragEvent
import android.view.View
import android.view.View.OnLongClickListener
import android.widget.LinearLayout
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.view.ViewCompat
import kotlinx.android.synthetic.main.drag_to_collect.view.*

/**
 * @author lmy
 * @功能: 移动拖拽底部删除功能样式
 * 跨进城拖拽传输数据
 * @Creat 2/15/21 2:34 PM
 * @Compony 465008238@qq.com
 */
class DragToCollectLayout(context: Context?, attrs: AttributeSet?) :
    ConstraintLayout(context, attrs) {
    private var dragStarter = OnLongClickListener { v ->
        val imageData = ClipData.newPlainText("name", v.contentDescription)
        //imageData参数是可以跨进程的
        ViewCompat.startDragAndDrop(v, imageData, DragShadowBuilder(v), null, 0)
    }
    private var dragListener: OnDragListener = CollectListener()

    override fun onFinishInflate() {
        super.onFinishInflate()
        //设置长按监听器 设置拖拽
        avatarView.setOnLongClickListener(dragStarter)
        logoView.setOnLongClickListener(dragStarter)
        //给collectorLayout设置拖拽监听器 设置松开的监听 然后添加落下的View信息
        collectorLayout.setOnDragListener(dragListener)
    }

    inner class CollectListener : OnDragListener {
        override fun onDrag(v: View, event: DragEvent): Boolean {
            when (event.action) {
                /**
                 * 松手的时候 触发
                 * ACTION_DROP可以获取startDrag中设置的随时都能拿到的数据
                 */
                DragEvent.ACTION_DROP -> if (v is LinearLayout) {
                    val textView = TextView(context)
                    textView.textSize = 16f
                    textView.text = event.clipData.getItemAt(0).text
                    v.addView(textView)
                }
            }
            return true
        }
    }
}
